package javaer.starter.util;

import javaer.starter.constant.StorePathEnum;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author yangzhen
 * @date 2023/6/15 11:24
 * @since 1.0.0
 */
public class ZIPUtil {

    /**
     * 文档压缩
     *
     * @param file     需要压缩的文件或目录
     * @param filename 压缩后的文件名称
     * @throws Exception
     */
    public static String decompress(File file, String filename) throws Exception {
        if (!Files.exists(StorePathEnum.ARCHIVE_PATH.getPath())) {
            Files.createDirectories(StorePathEnum.ARCHIVE_PATH.getPath());
        }
        String path = StorePathEnum.ARCHIVE_PATH.getDirectory() + "/" + filename;

        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(path));) {
            zipFile(file, zos, "");
        }
        return path;
    }

    public static void zipFile(File inFile, ZipOutputStream zos, String dir) throws IOException {
        if (inFile.isDirectory()) {
            File[] files = inFile.listFiles();
            if (files == null || files.length == 0) {
                zos.putNextEntry(new ZipEntry(dir + "/" + inFile.getName() + "/"));
                return;
            }

            for (File file : files) {
                String name = inFile.getName();
                if (!"".equals(dir)) {
                    name = dir + "/" + name;
                }
                zipFile(file, zos, name);
            }
        } else {
            String entryName;
            if (!"".equals(dir)) {
                entryName = dir + "/" + inFile.getName();
            } else {
                entryName = inFile.getName();
            }
            ZipEntry entry = new ZipEntry(entryName);
            zos.putNextEntry(entry);
            try (InputStream is = new FileInputStream(inFile)) {
                int len = 0;
                while ((len = is.read()) != -1) {
                    zos.write(len);
                }
            }
        }
    }
}
